﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using NLog;

namespace BookSourceVerification.utils;

/// <summary>
/// 文件加载器
/// </summary>
public class FileLoader
{
    private static Logger _logger = LogManager.GetCurrentClassLogger();

    // net8 可以使用 async IAsyncEnumerable
    public static IEnumerable<JObject> LoadFile(string? path)
    {
        path = path ?? throw new ArgumentNullException(nameof(path));
        using var sr = new StreamReader(path, Encoding.Default);
        using var reader = new JsonTextReader(sr);
        while (reader.Read())
        {
            if (reader.TokenType != JsonToken.StartArray) continue;
            // 遍历数组
            while (reader.Read() && reader.TokenType != JsonToken.EndArray)
            {
                if (reader.TokenType != JsonToken.StartObject) continue;
                yield return JObject.Load(reader);
            }
        }
    }

    public static void Test02()
    {
        const string filePath = @"C:\Users\zhazha\Desktop\965条精品源.json"; // 替换为你的文件路径
        using var sr = new StreamReader(filePath, Encoding.Default);
        using var reader = new JsonTextReader(sr);
        while (reader.Read())
        {
            if (reader.TokenType != JsonToken.StartArray) continue;
            // 遍历数组
            while (reader.Read() && reader.TokenType != JsonToken.EndArray)
            {
                if (reader.TokenType != JsonToken.StartObject) continue;
                var jsonObject = JObject.Load(reader);
                // 在这里处理每个JSON对象
                // Console.WriteLine(jsonObject.ToString());
                var p1 = jsonObject.Property("bookSourceGroup");
                if (p1 is not null) Console.WriteLine($"bookSourceGroup: {p1.Value}");
            }
        }
    }


    public static void Test01()
    {
        const string filePath = @"C:\Users\zhazha\Desktop\1234.json"; // 替换为你的文件路径
        const string targetPath = @"C:\Users\zhazha\Desktop\22222.json"; // 替换为你的文件路径

        using var sr = new StreamReader(filePath, Encoding.Default);
        using var reader = new JsonTextReader(sr);
        using var jsonTextWriter = new JsonTextWriter(new StreamWriter(targetPath, true, Encoding.Default));

        jsonTextWriter.WriteStartArray();
        while (reader.Read())
        {
            if (reader.TokenType != JsonToken.StartArray) continue;
            // 遍历数组
            while (reader.Read() && reader.TokenType != JsonToken.EndArray)
            {
                if (reader.TokenType != JsonToken.StartObject) continue;
                var jsonObject = JObject.Load(reader);
                // 在这里处理每个JSON对象
                Console.WriteLine(jsonObject.ToString());
                // 根据需要处理jsonObject，例如提取数据、存储等
                jsonObject.WriteTo(jsonTextWriter);
            }
        }

        jsonTextWriter.WriteEndArray();
        jsonTextWriter.Flush();
    }
}